import { getQuery, getValidatedQuery, H3, readBody } from "h3";
import { connection, find } from "../helper/mongo.ts";
import { response } from "../helper/response.ts";
import { isBlank } from "ph-utils";

const index = new H3()
  .get("/system-monitor", () => {
    return "SUCCESS";
  })
  .post("/trade_push", async (c) => {
    await getValidatedQuery(c, (data) => {
      return data && "token" in data && data.token === "f8cd550242441171c925ce40de897f2a";
    });
    const body = await readBody<Record<string, any>>(c);
    if (body) {
      const accountId = body.accountId;
      const date = body.date;
      // 账户信息
      await connection("account").deleteMany({ accountId, date });
      await connection("account").insertOne({
        accountId,
        date,
        ...body.account,
      });
      // 订单信息
      await connection("order").deleteMany({ accountId, date });
      await connection("order").insertMany(
        body.order.map((order: any) => ({
          accountId,
          date,
          ...order,
        })),
      );
      // 持仓信息
      await connection("position").deleteMany({ accountId, date });
      await connection("position").insertMany(
        body.position.map((position: any) => ({
          accountId,
          date,
          ...position,
        })),
      );
    }
    return response();
  })
  .get("/accounts", async (c) => {
    const query = getQuery(c);
    const filter: Record<string, any> = {};
    if (!isBlank(query.date)) {
      filter.date = query.date;
    }
    if (!isBlank(query.account)) {
      filter.accountId = query.account;
    }
    let fields: string[] | undefined;
    if (query.fields) {
      fields = query.fields.split(",");
    }
    const data = await find({
      connection: "account",
      filter,
      fields,
      sort: { date: -1 },
    });
    return response(data);
  });

export default index;
